﻿using System;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;

namespace PKTools.Database
{
    public class MsSql : Sql
    {
        public MsSql(bool openTransaction = false, string connection = null)
            : base(openTransaction, connection)
        {
            this.command = new SqlCommand(
                string.Empty,
                new SqlConnection(this.connection));
        }

        public override DbParameter AddInput(string key, object value, Type type = null)
        {
            var
                p = new SqlParameter(key, value ?? DBNull.Value);
            this.command.Parameters.Add(p);
            return p;
        }

        public override DbParameter AddOutput(string key, Type type)
        {
            type = GetFinalType(type);

            object
                value = null;
            if (type.IsValueType)
                value = Activator.CreateInstance(type);

            var
                p = new SqlParameter(key, value)
                {
                    Direction = ParameterDirection.Output
                };
            
            this.command.Parameters.Add(p);
            return p;
        }

        public override decimal GetIdentity()
        {
            Clear();
            return (decimal)ExecuteScalar("SELECT @@IDENTITY");
        }

        public override string FormatColumn(string column)
        {
            return '[' + column + ']';
        }

        protected override string GetTopSelectQuery(string fieldsQuery, string tableQuery, string whereQuery, int top)
        {
            return string.Format("SELECT{0} {1} FROM {2} WHERE {3}", 
                top == -1 ? string.Empty : " TOP " + top,
                fieldsQuery, tableQuery, whereQuery);
        }
    }
}
